package common.util;

import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 *
 * @author shousuke
 */
public class DbUtil {

    public static Object getSingleResult(EntityManager em, String queryName, Map<String, Object> param) {
        Query query = em.createNamedQuery(queryName);
        for (String i : param.keySet()) {
            query.setParameter(i, param.get(i));
        }
        try {
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        } catch (NonUniqueResultException e) {
            FacesUtil.addErrorMessage(e.getLocalizedMessage());
            return null;
        }
    }

    public static List getResultList(EntityManager em, String queryName, Map<String, Object> param) {
        Query query = em.createNamedQuery(queryName);
        for (String i : param.keySet()) {
            query.setParameter(i, param.get(i));
        }
        return query.getResultList();
    }
}
